package com.edu.rpc.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

/**
 * 1.自定义请求授权规则：     .authorizeHttpRequests
 * 2.自定义登录规则：        .formLogin
 * 3.自定义用户信息查询规则：  .userDetailsService
 * 4.开启方法级别的精确权限控制：@EnableMethodSecurity + @PreAuthorize("hasAuthority('world_exec')")
 * <p>
 * <p>
 * * Security场景的自动配置：
 * * SecurityAutoConfiguration/SpringBootWebSecurityConfiguration/SecurityFilterAutoConfiguration
 * * 1、security的所有配置在SecurityProperties: 以spring.security开头
 * * 2、默认SecurityFilterChain组件：
 * * - - 所有请求都需要认证：登录
 * * - - 开启表单登录: SpringSecurity提供一个默认登录页，未经登录的所有请求都需要登录
 * * - - httpbasic方式登录
 * * 3、@EnableWebSecurity 生效
 * * - - 1、WebSecurityConfiguration生效：web安全配置
 * * - - 2、HttpSecurityConfiguration生效：http安全规则
 * * - - 3、@EnableGlobalAuthentication 激活全局认证
 * * --- AuthenticationConfiguration
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class AppSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // 1. 修复路径匹配规则
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/", "/index.html", "/welcome").permitAll()  // 精确匹配根路径及变体
                        .requestMatchers("/static/**", "/*.ico", "/*.json", "/*.css").permitAll() // 放行静态资源
                        .anyRequest().authenticated()
                )
//                // 2. 显式禁用CSRF（前后端分离场景）
//                .csrf(AbstractHttpConfigurer::disable)
//                // 3. 启用无状态会话管理
//                .sessionManagement(session ->
//                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//                )
                .formLogin(form -> form.loginPage("/login").permitAll());
        return httpSecurity.build();
    }

    // 查询用户详情
    @Bean
    UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        UserDetails userA = User.withUsername("userA")
                .password(passwordEncoder.encode("userA"))
                .roles("admin")
                .authorities("file_read", "file_write")
                .build();
        UserDetails userB = User.withUsername("userB")
                .password(passwordEncoder.encode("userB"))
                .roles("hr")
                .authorities("file_read")
                .build();
        UserDetails userC = User.withUsername("userC")
                .password(passwordEncoder.encode("userC"))
                .roles("coder")
                .authorities("file_write")
                .build();
        // 默认内存中保存所有用户信息
        return new InMemoryUserDetailsManager(userA, userB, userC);
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
